package com.kuanter.kuanterauto.activity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.adapter.MerchanServiceAdapter;
import com.kuanter.kuanterauto.entity.MerchanServiceInfo;
import com.kuanter.kuanterauto.entity.SiteInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.Utility;

/**
 * 网点详情
 * @author kuanter
 *
 */
@Deprecated
public class MerchantActivity extends Activity {
	ImageView merchan_image;  //商户图片展示
	ListView merchan_serice;  //商户服务列表
	RelativeLayout bt_webSite_call;  //打电话给商户
	RelativeLayout bt_webSite_getRoute;  //用户位置到商户路线
	
	List<MerchanServiceInfo> list_merchanService;
	
	String id;  //商户ID
	int position;  //商户在列表中的位置
	
	SiteInfo first;
	RelativeLayout close_first;
	int pre_position;
	
	SiteInfo second;
	RelativeLayout close_second;
	int next_position;
	
	TextView kuanter_middle; //网点名字
	
	int screenWidth;
	int screenHeight;
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == HttpTask.RESULT_OK) {
				String result = (String) msg.obj;
				//json解析
			}
			super.handleMessage(msg);
		}
		
	};
	
	ScrollView scrollView;
	
	ImageView imageView33;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.kuanter_merchan);
		scrollView = (ScrollView) findViewById(R.id.scrollView);
		close_first = (RelativeLayout) findViewById(R.id.close_1);
		close_first.setBackgroundResource(R.drawable.websitedetailinfo);
		close_first.setClickable(true);
		
		close_second = (RelativeLayout) findViewById(R.id.close_2);
		close_second.setClickable(true);
		close_second.setBackgroundResource(R.drawable.websitedetailinfo);
		
		imageView33 = (ImageView) findViewById(R.id.imageView33);
		
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenWidth = dm.widthPixels;
		screenHeight = dm.heightPixels;
		
		Intent intent = getIntent();
		id = intent.getStringExtra("siteID");
		position = intent.getIntExtra("sitePosition", -1);
		if(position >= 0) {
			if(SitesActivity.getCurrentData().size() > 2) {
				
				if(position == SitesActivity.getCurrentData().size() -1 ) {  //最后一个数据
					first = SitesActivity.getCurrentData().get(position - 2);
					pre_position = position - 2;
					
					second = SitesActivity.getCurrentData().get(position - 1);
					next_position = position - 1;
				} else if(position == SitesActivity.getCurrentData().size() - 2) {  //倒数第二个
					first = SitesActivity.getCurrentData().get(position - 1);
					pre_position = position - 1;
					
					second = SitesActivity.getCurrentData().get(position + 1);
					next_position = position + 1;
				} else {
					first = SitesActivity.getCurrentData().get(position + 1);
					pre_position = position + 1;
					
					second = SitesActivity.getCurrentData().get(position + 2);
					next_position = position + 2;
				}
			} else if(SitesActivity.getCurrentData().size() == 2) {
				if(position == 0) {
					next_position = 1;
					second = SitesActivity.getCurrentData().get(1);
					close_first.setVisibility(View.GONE);
					imageView33.setVisibility(View.GONE);
				} else if(position == 1) {
					pre_position = 0;
					first = SitesActivity.getCurrentData().get(0);
					close_second.setVisibility(View.GONE);
				}
			} else {
				close_first.setVisibility(View.GONE);
				close_second.setVisibility(View.GONE);
			}
			
		}
		
		initView();
		
		if(id != null && !id.equals("")) {
			//TODO 请求数据
			DataLoader loader = new DataLoader(this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair param = new BasicNameValuePair("id", id);
			params.add(param);
			loader.DisplayData("地址", params, mHandler, "", false);
		}
		
	}

	private void initView() {
		kuanter_middle = (TextView) findViewById(R.id.kuanter_middle);
		kuanter_middle.setText(SitesActivity.getCurrentData().get(position).getSiteName());
		
		merchan_image = (ImageView) findViewById(R.id.merchan_image);
		new DownLoadImage().execute("http://192.168.0.15:8080/examples/a.jpg");
		
//		merchan_serice = (ListView) findViewById(R.id.merchan_serice);
		bt_webSite_call = (RelativeLayout) findViewById(R.id.bt_webSite_call);
		bt_webSite_getRoute = (RelativeLayout) findViewById(R.id.bt_webSite_getRoute);
		
		list_merchanService = new ArrayList<MerchanServiceInfo>();
		MerchanServiceAdapter adapter = new MerchanServiceAdapter(getLayoutInflater());
		merchan_serice.setAdapter(adapter);
		Utility.setListViewHeightBasedOnChildren(merchan_serice);
		
		bt_webSite_getRoute.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
//				Intent intent = new Intent(MerchantActivity.this, SiteRouteActivity.class);
				Intent intent = new Intent(MerchantActivity.this, RoutePlanActivity.class);
				intent.putExtra("latitude", 30.642237);
				intent.putExtra("longtitude",114.292559);
				startActivity(intent);
			}
		});
		
		
		final TextView tv_first_id = (TextView) close_first.findViewById(R.id.site_id);
		TextView tv_first_siteName = (TextView) close_first.findViewById(R.id.site_name);
		TextView tv_first_sitePrice = (TextView) close_first.findViewById(R.id.site_price);
		TextView tv_first_siteDisatance = (TextView) close_first.findViewById(R.id.site_distance);
//		ImageView iv_first_siteStar = (ImageView) close_first.findViewById(R.id.site_star);
		
		if(first != null) {
			tv_first_id.setText(first.getId() + "");
			tv_first_siteName.setText(first.getSiteName());
			tv_first_sitePrice.setText("价格： " + first.getMaxServicePrice() + "元/次");
			tv_first_siteDisatance.setText(first.getSiteDistance());
			close_first.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent intent = new Intent(MerchantActivity.this, MerchantActivity.class);
					intent.putExtra("siteID", tv_first_id.getText().toString());
					intent.putExtra("sitePosition", pre_position);
					startActivity(intent);
					finish();
				}
			});
		}

		
		final TextView tv_second_id = (TextView) close_second.findViewById(R.id.site_id);
		TextView tv_second_siteName = (TextView) close_second.findViewById(R.id.site_name);
		TextView tv_second_sitePrice = (TextView) close_second.findViewById(R.id.site_price);
		TextView tv_second_siteDisatance = (TextView) close_second.findViewById(R.id.site_distance);
//		ImageView iv_second_siteStar = (ImageView) close_second.findViewById(R.id.site_star);
		
		if(second != null) {
			
			tv_second_id.setText(second.getId() + "");
			tv_second_siteName.setText(second.getSiteName());
			tv_second_sitePrice.setText("价格： " + second.getMaxServicePrice() + "元/次");
			tv_second_siteDisatance.setText(second.getSiteDistance());
			
			close_second.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent intent = new Intent(MerchantActivity.this, MerchantActivity.class);
					intent.putExtra("siteID", tv_second_id.getText().toString());
					intent.putExtra("sitePosition", next_position);
					startActivity(intent);
					finish();
				}
			});
		}
		
	}

	public void exit(View view) {
		finish();
	}
	
	
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if(hasFocus) {
			if(scrollView != null) {
				scrollView.scrollTo(0, 0);  //滚动到顶部
			}
		}
		super.onWindowFocusChanged(hasFocus);
	}



	class DownLoadImage extends AsyncTask<String, Void, Void> {
		Bitmap bitmap;

		@Override
		protected Void doInBackground(String... params) {
			String url = params[0];
			InputStream is = getStream(url);
			//图片处理
			BitmapFactory.Options option = new BitmapFactory.Options();
            option.inJustDecodeBounds = true;
            
            if(is != null) {
            	bitmap = BitmapFactory.decodeStream(is,null,option);
            	int width = option.outWidth / screenWidth;
            	if(width > 1) {
            		option.inSampleSize = width;
            	} else {
            		width = 1;
            	}
            	option.inJustDecodeBounds = false;
            	
            	InputStream is_1 = getStream(url);
            	if(is_1 != null) {
            		bitmap = BitmapFactory.decodeStream(is_1, null, option);
            		Matrix matrix = new Matrix();
            		int myHeight = 250;
            		float f_yScale = ((float)myHeight) / option.outHeight;
            		float f_xScale = ((float)screenWidth) /option.outWidth;
            		matrix.postScale(f_xScale, f_yScale);
            		bitmap = Bitmap.createBitmap(bitmap, 0, 0, option.outWidth, option.outHeight,matrix,true);
            		
            		ByteArrayOutputStream baos = new ByteArrayOutputStream();
            		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            		int quality = 100;
            		while(baos.toByteArray().length /1024 > 200) {  //大于200k就压缩
            			baos.reset();
            			bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            			quality -= 2;
            		}
            		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            		bitmap = BitmapFactory.decodeStream(bais, null, null);
            	}
            }
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if(bitmap != null) {
				merchan_image.setImageBitmap(bitmap);
			}
			super.onPostExecute(result);
		}
		
		public InputStream getStream(String url) {
			InputStream is = null;
			URL u;
			try {
				u = new URL(url);
				URLConnection conn = u.openConnection();
				conn.connect();
				is = conn.getInputStream();
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return is;
		}
		
	}
	
}
